package co.fitstart.admin.web.controller.report;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;

import co.fitstart.admin.entity.report.UnfinishedRoundReport;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CoachService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.ReportService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.round.CourseRoundAttribute;
import co.fitstart.entity.course.round.CourseRoundResult;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;

/**
 * 在营学员报表
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("/unfinished-round-reports")
@MenuSetting("menu-report")
public class UnfinishedRoundReportController {
    
    private static final Logger logger = LoggerFactory.getLogger(UnfinishedRoundReportController.class);
    
    @Autowired
    private SiteService siteService;
    
    @Autowired
    private ReportService reportService;
    
    @Autowired
    private CoachService coachService;
    
    @Autowired
    private PrincipalService principalService;
    
    /**
     * 
     * @param login
     * @param siteId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-unfinished-round-report")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(name = "site", required = false) Long siteId) {
        ModelAndView modelAndView = new ModelAndView("report/unfinished-round-report-list");
        
        Site site = null;
        if(!login.hasSite() && siteId != null) {
            site = siteService.load(siteId);
        }else if (login.hasSite()){
            site = login.getSite();
        }
        
        List<UnfinishedRoundReport> reports = new ArrayList<>();
        
        if(site == null && (login.isAreaManager() || login.isAreaServer())) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                reports = reportService.listUnfinishedRoundStat(sites, null);
            }
        } else {
            reports = reportService.listUnfinishedRoundStat(site, null);
        }
        
        modelAndView.addObject("reports", reports);
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 导出在营学员-页面
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export() {
        ModelAndView modelAndView = new ModelAndView("report/unfinished-round-report-export");
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/coaches", method = RequestMethod.POST)
    public @ResponseBody String coaches(@Secure Login login,
                                        @RequestParam(value = "siteId", required = false) Long siteId) {
        
        Result result = new Result();
        
        try {
            Site site = null;
            if(!login.hasSite() && siteId != null) {
                site = siteService.load(siteId);
            }else if (login.hasSite()){
                site = login.getSite();
            }
            
            List<Site> sites = new ArrayList<>();
            
            if(site != null) {
                sites.add(site);
            } else if(login.isAreaManager() || login.isAreaServer()) {
                Principal principal = principalService.load(Principal.class, login.getId());
                
                sites = siteService.listSite(principal);
            } else {
                sites = siteService.loadAll();
            }
            
            List<Principal> coaches = coachService.listCoach(sites);
            
            result.success().data("coaches", coaches).data("coachAmount", coaches.size()).message("获取门店教练成功");
            
        } catch (Exception e) {
            
            logger.error("coaches() error:", e);
            result.fail().message("获取门店教练失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 导出在营学员
     * @param login
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "siteId", required=false) Long siteId,
                                 @RequestParam(value = "coachId", required=false) Long coachId,
                                 @RequestParam(value = "beginDate", required=false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate", required=false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("unfinished-round-report.xls"));
        
        Site site = null;
        if(!login.hasSite() && siteId != null) {
            site = siteService.load(siteId);
        }else if (login.hasSite()){
            site = login.getSite();
        }
        
        Principal coach = null;
        if(coachId != null) {
            coach = coachService.load(coachId);
        }
        
        List<Site> sites = new ArrayList<>();
        
        if(site != null) {
            sites.add(site);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            sites = siteService.listSite(principal);
        } else {
            sites = siteService.loadAll();
        }
        
        List<UnfinishedRoundReport> reports = new ArrayList<>();
        List<CourseRound> courseRounds = new ArrayList<>();
        
        if(!sites.isEmpty()) {
            reports = reportService.listUnfinishedRoundStat(sites, coach);
            courseRounds = reportService.listUnfinishedRound(sites, coach);
            Map<Long, String> tags = reportService.listTags(courseRounds);
            Map<Long, CourseRoundResult> results = reportService.mapCourseRoundResult(sites, coach);
            
            modelAndView.addObject("tags", tags);
            modelAndView.addObject("results", results);
            
            if(beginDate != null && endDate != null) {
                Map<Long, Long> cancelRecords = reportService.listScheduleCancelStat(sites, coach, beginDate, endDate);
                
                modelAndView.addObject("cancelRecords", cancelRecords);
                modelAndView.addObject("time", "(" + DateFormatUtils.format(beginDate, "yyyy-MM-dd") + "至" + DateFormatUtils.format(endDate, "yyyy-MM-dd") + ")");
            }
        }
        
        List<CourseRoundAttribute> courseRoundAttributes = reportService.listDelayRecord(new Date());
        Map<String, List<CourseRoundAttribute>> courseRoundAttributesMap = CollectionUtils.constructMapValuesFromList(courseRoundAttributes, "courseRound.id");
        modelAndView.addObject("courseRoundAttributesMap", courseRoundAttributesMap);
        
        modelAndView.addObject("reports", reports);
        modelAndView.addObject("courseRounds", courseRounds);
//        modelAndView.addObject("targets",  CollectionUtils.constructMapValueFromList(reportService.listStudentTargetData(sites, coach), "courseRound.id"));
        modelAndView.addObject("site", site);
        modelAndView.addObject("coach", coach);
        
        NumberFormat numFmt = new DecimalFormat("0");
        modelAndView.addObject("numFmt", numFmt);
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
}
